package com.kuqi.ViewComponent.PullUpLoad;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.Scroller;

public class PullUpToLoadMore extends ViewGroup {

    // 所有子项view列表
    private View[] views;
    // 每个子项之间的分界坐标（数量会比views少一个）
    private int[] departPositions;
    // 当前位置索引
    private int currPosition = 0;
    // 最顶上和最底下的两个界面
    private View topView, bottomView;

    // 用于计算手动滑动速度工具
    private VelocityTracker velocityTracker = VelocityTracker.obtain();

    // 缓动
    private Scroller scroller = new Scroller(getContext());

    // 状态回调
    private PullIndexListener indexListener;


    /**
     * 按下时的坐标
     */
    int lastY;
    int lastX;
    /**
     * 最小滑动距离
     */
    public int scaledTouchSlop;

    /**
     * 滑动速度限制
     */
    int speed = 200;

    public PullUpToLoadMore(Context context) {
        super(context);
        init();
    }

    public PullUpToLoadMore(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PullUpToLoadMore(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        post(new Runnable() {
            @Override
            public void run() {
                int childNum = getChildCount();
                views = new View[childNum]; // index 从0到childNum-1
                for(int i=0;i<childNum;i++){
                    views[i] = getChildAt(i);
                }
                topView = getChildAt(0);
                bottomView = getChildAt(childNum-1);
                int departNum = childNum - 1;
                departPositions = new int[departNum]; // 分界肯定比模块数量少一个 即depart[0]在view[0]和view[1]之间
                for(int j=0;j<departNum;j++){
                    departPositions[j] = views[j].getBottom();
                }
                scaledTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //防止子View禁止父view拦截事件
        this.requestDisallowInterceptTouchEvent(false);
        return super.dispatchTouchEvent(ev);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int y = (int) event.getY();
        int x = (int) event.getX();

        velocityTracker.addMovement(event); //用于追踪手指滑动速度

        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                int dy = lastY - y; // 本次滑动移动的距离
                if (getScrollY() + dy < 0) { // 如果当前画布纵坐标 + 移动距离会低于画布原点
                    dy = 0; // 锁死在画布远点（顶点）
                } else if (getScrollY() + dy + getHeight() > bottomView.getBottom()) { // 如果当前视窗底部滑动后超过了最底部的view
                    dy = bottomView.getBottom() - getHeight() - getScrollY(); // 锁定在屏幕最下端
                }
                scrollBy(0, dy);
                break;
            case MotionEvent.ACTION_UP:
                velocityTracker.computeCurrentVelocity(1000);
                float yVelocity = velocityTracker.getYVelocity(); // 计算手指滑动的速度（Y方向的）
                if (currPosition == 0) { // 如果当前是第一个界面
                    if (yVelocity < 0 && (Math.abs(yVelocity) > speed)) { // 向上滑且滑动速度大于speed
                        smoothScroll(departPositions[currPosition]); // 页面自动转到下一章的显示位置
                        currPosition++;
                    }else{ // 速度不够
                        smoothScroll(departPositions[0]- getHeight());
                    }
                } else if (currPosition == (views.length-1)){ // 当前是最后一个界面
                    if (yVelocity > 0 && (Math.abs(yVelocity) > speed)) {// 向下滑且滑动速度大于speed
                        smoothScroll(departPositions[currPosition - 1] - getHeight()); // -1是因为depart的索引永远比后一个小1
                        currPosition--;
                    }else{ // 速度不够
                        smoothScroll(departPositions[currPosition - 1]);
                    }
                }else{ // 非最前与最后的中间界面
                    if (yVelocity > 0 && (Math.abs(yVelocity) > speed)) {// 向下滑且滑动速度大于speed
                        smoothScroll(departPositions[currPosition - 1] - getHeight()); // -1是因为depart的索引永远比后一个小1
                        currPosition--;
                    }else if (yVelocity < 0 && (Math.abs(yVelocity) > speed)) { // 向上滑且滑动速度大于speed
                        smoothScroll(departPositions[currPosition]); // 页面自动转到下一章的显示位置
                        currPosition++;
                    }else{ // 速度值太小，回归原位置
                        smoothScroll(departPositions[currPosition - 1]);
                    }
                }
                Log.e("当前页面index", String.valueOf(currPosition));
                boolean isFirst = false;
                boolean isEnd = false;
                if(currPosition == 0){
                    indexListener.reachFirst();
                    isFirst = true;
                }else if(currPosition == (views.length-1)){
                    indexListener.reachEnd();
                    isEnd = true;
                }
                indexListener.currentChanged(currPosition, isFirst, isEnd);
                break;
            default:
                break;
        }
        lastY = y;
        lastX = x;
        return true;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measureChildren(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int childCount = getChildCount();
        int childTop = 0;
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            child.layout(l, childTop, r, childTop + child.getMeasuredHeight());
            childTop += child.getMeasuredHeight();
        }
    }

    /**
     * 通过Scroller实现弹性滑动
     * @param startY
     */
    private void smoothScroll(int startY) {
        int dy = startY - getScrollY();
        scroller.startScroll(getScrollX(), getScrollY(), 0, dy);
        invalidate();
    }

    @Override
    public void computeScroll() {
        if (scroller.computeScrollOffset()) {
            scrollTo(scroller.getCurrX(), scroller.getCurrY());
            postInvalidate();
        }
    }


    /**
     * 注册状态回调函数
     * @param indexListener 状态回调函数
     */
    public void setPullIndexListener(PullIndexListener indexListener){
        this.indexListener = indexListener;
    }


    /**
     * 接口， 当状态改变触发下面的函数
     */
    public interface PullIndexListener{
        void reachFirst();
        void reachEnd();
        void currentChanged(int currentIndex, boolean isFirst, boolean isEnd);
    }

}
